package com.teamsapp.article.service;

import com.teamsapp.article.dto.ArticleDTO;
import com.teamsapp.article.dto.CreateArticleDTO;
import com.teamsapp.article.dto.PageResponse;
import com.teamsapp.article.dto.UpdateArticleDTO;
import com.teamsapp.article.model.Article;
import com.teamsapp.article.model.ArticleStatus;
import com.teamsapp.article.repository.ArticleRepository;
import com.teamsapp.article.util.SnowflakeIdGenerator;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ArticleService {
    private final ArticleRepository articleRepository;
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private static final String DEFAULT_AUTHOR = "System User"; // 临时使用，实际应该从认证系统获取

    @Transactional(readOnly = true)
    public PageResponse<ArticleDTO> getAllArticles(int page, int pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        Page<Article> articlePage = articleRepository.findLatestVersions(pageRequest);
        
        List<ArticleDTO> articleDTOs = articlePage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
                
        return new PageResponse<>(
            articleDTOs,
            articlePage.getTotalElements(),
            page,
            pageSize
        );
    }

    @Transactional(readOnly = true)
    public ArticleDTO getArticleById(String id) {
        return articleRepository.findById(id)
                .map(this::convertToDTO)
                .orElseThrow(() -> new EntityNotFoundException("文章不存在"));
    }

    @Transactional
    public ArticleDTO createArticle(CreateArticleDTO createArticleDTO) {
        Article article = new Article();
        article.setTitle(createArticleDTO.getTitle());
        article.setContent(createArticleDTO.getContent());
        article.setCoverImage(createArticleDTO.getCoverImage());
        article.setSummary(createArticleDTO.getSummary());
        article.setStatus(ArticleStatus.fromValue(createArticleDTO.getStatus()));
        article.setId(snowflakeIdGenerator.nextId());
        article.setAuthor(DEFAULT_AUTHOR);
        Article savedArticle = articleRepository.save(article);
        
        // 返回第一页的数据
        PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
        Page<Article> articlePage = articleRepository.findLatestVersions(pageRequest);
        List<ArticleDTO> articleDTOs = articlePage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
                
        return convertToDTO(savedArticle);
    }

    @Transactional
    public ArticleDTO updateArticle(String id, UpdateArticleDTO updateArticleDTO) {
        Article article = articleRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("文章不存在"));

        // 保存原始状态
        ArticleStatus originalStatus = article.getStatus();

        // 如果是已发布的文章要改为草稿，创建新的草稿文章
        if (originalStatus == ArticleStatus.PUBLISHED && 
            updateArticleDTO.getStatus() != null && 
            ArticleStatus.fromValue(updateArticleDTO.getStatus()) == ArticleStatus.DRAFT) {
            
            Article draftArticle = new Article();
            BeanUtils.copyProperties(article, draftArticle, "id", "createTime", "status", "originalId");
            
            // 更新草稿文章的内容
            if (updateArticleDTO.getTitle() != null) {
                draftArticle.setTitle(updateArticleDTO.getTitle());
            }
            if (updateArticleDTO.getContent() != null) {
                draftArticle.setContent(updateArticleDTO.getContent());
            }
            if (updateArticleDTO.getCoverImage() != null) {
                draftArticle.setCoverImage(updateArticleDTO.getCoverImage());
            }
            if (updateArticleDTO.getSummary() != null) {
                draftArticle.setSummary(updateArticleDTO.getSummary());
            }
            
            draftArticle.setId(snowflakeIdGenerator.nextId());
            draftArticle.setOriginalId(article.getId());
            draftArticle.setStatus(ArticleStatus.DRAFT);
            
            return convertToDTO(articleRepository.save(draftArticle));
        }

        // 如果是草稿文章要发布
        if (originalStatus == ArticleStatus.DRAFT && 
            updateArticleDTO.getStatus() != null && 
            ArticleStatus.fromValue(updateArticleDTO.getStatus()) == ArticleStatus.PUBLISHED) {
            
            // 如果有原始文章，更新原始文章
            if (article.getOriginalId() != null) {
                Article publishedArticle = new Article();
                BeanUtils.copyProperties(article, publishedArticle, "id", "originalId");
                publishedArticle.setId(article.getOriginalId());
                publishedArticle.setOriginalId(null);
                publishedArticle.setStatus(ArticleStatus.PUBLISHED);
                
                Article savedArticle = articleRepository.save(publishedArticle);
                articleRepository.delete(article);
                return convertToDTO(savedArticle);
            }
            
            // 如果没有原始文章，直接更新状态
            article.setStatus(ArticleStatus.PUBLISHED);
        }

        // 普通的更新操作
        if (updateArticleDTO.getTitle() != null) {
            article.setTitle(updateArticleDTO.getTitle());
        }
        if (updateArticleDTO.getContent() != null) {
            article.setContent(updateArticleDTO.getContent());
        }
        if (updateArticleDTO.getCoverImage() != null) {
            article.setCoverImage(updateArticleDTO.getCoverImage());
        }
        if (updateArticleDTO.getSummary() != null) {
            article.setSummary(updateArticleDTO.getSummary());
        }
        
        // 更新状态（如果不是特殊状态转换的情况）
        if (updateArticleDTO.getStatus() != null) {
            ArticleStatus newStatus = ArticleStatus.fromValue(updateArticleDTO.getStatus());
            if (originalStatus != ArticleStatus.PUBLISHED || newStatus != ArticleStatus.DRAFT) {
                article.setStatus(newStatus);
            }
        }

        return convertToDTO(articleRepository.save(article));
    }

    @Transactional
    public void deleteArticle(String id) {
        if (!articleRepository.existsById(id)) {
            throw new EntityNotFoundException("文章不存在");
        }
        articleRepository.deleteById(id);
    }

    @Transactional(readOnly = true)
    public PageResponse<ArticleDTO> getPublishedArticles(int page, int pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        // 使用 PUBLISHED 状态（值为1）查询
        Page<Article> articlePage = articleRepository.findByStatus(ArticleStatus.PUBLISHED, pageRequest);
        
        List<ArticleDTO> articleDTOs = articlePage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
                
        return new PageResponse<>(
            articleDTOs,
            articlePage.getTotalElements(),
            page,
            pageSize
        );
    }

    private ArticleDTO convertToDTO(Article article) {
        ArticleDTO dto = new ArticleDTO();
        BeanUtils.copyProperties(article, dto);
        dto.setStatus(article.getStatus().getValue());  // 设置状态为整数值
        return dto;
    }
}